<?php

require_once 'include/config.php';
require_once 'include/http.php';

$wechat = new wechat();

class wechat{
    
    private $appid = '';
    private $appsecret = '';
    private $http = '';
    public function __construct() {
        $this->appid = constant('APPID');
        $this->appsecret = constant('APPSECRET');
        $this->http = new http();
        //获取接口
        $type = isset($_GET['type'])?$_GET['type']:"";
        //获取access_token
        $access_token = $this->getAccessToken();
        $ret = '';
        if($access_token){
            switch ($type) {
                case 'create_menu':#创建菜单
                    $ret = $this->createMenu($access_token);
                    break;
                case 'create_more_menu':#创建个性化菜单
                    $ret = $this->createMoreMenu($access_token);
                    break;
                case 'del_menu':
                    $ret = $this->delMenu($access_token);
                    break;
            }
        }
        //读取结果
        echo $ret;
    }
    //获取缓存
    public function getAccessToken() {
        //定义access_token缓存文件名称
        $cacheFile = __DIR__.'/log/access_token.xml';
        //判断是否存在文件，时间是否过期，若没有，直接读取文件的access_token
        if(is_file($cacheFile) && filemtime($cacheFile)+7200 > time()){
            $access_token = file_get_contents($cacheFile);
            return $access_token;
        }
        //get请求
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        $data = $this->http->http_request($url);
        //获取access_token
        $access_token = json_decode($data,true)['access_token'];
        //记录access_token
        file_put_contents($cacheFile, $access_token);
        return $access_token;
    }
    //创建菜单
    private function createMoreMenu($access_token) {
        //获取菜单
        $menuList = include './include/more_menu.php';
//        echo $menuList;exit;
        //创建自定义菜单路由
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
        //发起请求
        $json = $this->http->http_request($url,$menuList);
        //返回json
        return $json;
    }
    //创建菜单
    private function createMenu($access_token) {
        //获取菜单
        $menuList = json_encode(include './include/menu.php',JSON_UNESCAPED_UNICODE);
        //创建自定义菜单路由
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
        //发起请求
        $json = $this->http->http_request($url,$menuList);
        //返回json
        return $json;
    }
    //删除菜单
    private function delMenu($access_token) {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$access_token}";
        $json = $this->http->http_request($url);
        return $json;
    }
    
}

